//导入 express
const express = require('express');
//导入定义验证规则的包
const joi = require('@hapi/joi');
//创建服务器对象
const app = express();
//解决跨域
app.use(require('cors')());

//响应数据的中间件
app.use(function (req, res, next) {
    //code 1表示失败 0表示成功
    res.cc = function (err, code = 1) {
        res.send({
            //状态
            code,
            // 状态描述，如果 err 是 Error 实例，则使用 err.message，否则使用 err
            message: err instanceof Error ? err.message : err
        });
    };
    next();
});

//配置解析表单请求体
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

// POST /api/upload
const multer = require('multer');
const path = require('path');

// 配置存储规则
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'public/uploads/manure/'); // 保存到本地目录
    },
    filename: (req, file, cb) => {
        const uniqueName = `${Date.now()}_${Math.random().toString(36).slice(2)}${path.extname(file.originalname)}`;
        cb(null, uniqueName); // 生成唯一文件名（如：1694768400000_abc123.jpg）
    }
});

const upload = multer({
    storage: storage,
    limits: { fileSize: 5 * 1024 * 1024 }, // 限制5MB
    fileFilter: (req, file, cb) => {       // 限制文件类型
        if (['image/jpeg', 'image/png'].includes(file.mimetype)) {
            cb(null, true);
        } else {
            cb(new Error('仅支持 JPG/PNG 格式'));
        }
    }
});

// 在路由中使用
app.post('/api/upload', upload.single('image'), (req, res) => {
    const imageUrl = `/uploads/manure/${req.file.filename}`; // 保存相对路径
    res.json({ code: 200, data: { url: imageUrl } });
});

// Express 配置静态目录
app.use('/uploads', express.static('public/uploads'));

//导入用户管理模块
const router = require('./router/user.js');
app.use('/user', router);

//导入畜牧管理模块
const cattleRouter = require('./router/cattle.js');
app.use('/cattle', cattleRouter);

//导入粪源管理模块
const manureRouter = require('./router/manure.js');
app.use('/manure', manureRouter);

//导入出入栏管理模块
const movementRouter = require('./router/movement.js');
app.use('/movement', movementRouter);

// 确保静态资源目录存在
const fs = require('fs');
const uploadDir = 'public/uploads/manure';
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}


//定义错误级别的中间件
app.use(function (err, req, res, next) {
    if (err instanceof multer.MulterError) {
        return res.status(400).json({ 
          code: 1, 
          message: `文件上传错误: ${err.message}` 
        });
      }
    // 验证失败的错误
    if (err instanceof joi.ValidationError) {
        return res.cc(err);
    } else {
        //未知错误
        return res.cc(err);
    }
});
//启动服务器
app.listen(3007, () => {
    console.log('api server runing at http://127.0.0.1');
});    